﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web.Http;
using log4net;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.BLL.CloudCard;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;
using Matrix.MaKaYunShang.Model.Enum;

namespace Matrix.MaKaYunShang.ApiService.Controllers
{
    /// <summary>
    /// 店铺API
    /// </summary>
    public class ShopApiController : BaseApiController
    {
        private readonly ILog _fileLog = LogManager.GetLogger(typeof(ShopApiController));
        private readonly ShopsBLL _shopsBll = new ShopsBLL();
        private readonly ShopNoticeBLL _shopNoticeBll = new ShopNoticeBLL();
        private readonly CloudCardBll _cloudCardBll = new CloudCardBll();
        // POST api/ShopApi/MatchShops/
        /// <summary>
        /// 获取用户当前经纬度所能匹配的店铺列表
        /// </summary>
        /// <param name="longitude">经度</param>
        /// <param name="latitude">纬度</param>
        /// <param name="searchKeyword">搜索店铺名称</param>
        /// <returns>返回店铺信息列表</returns>
        [HttpPost]
        public Result<List<Shops>> MatchShops(string longitude, string latitude, string searchKeyword)
        {
            _fileLog.Info("ShopApiController | MatchShops | 坐标 >longitude:" + longitude + ",latitude:" + latitude);
            var checkResult = CheckPermission("ShopApiController | MatchShops");
            if (!checkResult.Status)
            {
                return new Result<List<Shops>>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }

            if (string.IsNullOrWhiteSpace(longitude) || string.IsNullOrWhiteSpace(latitude))
            {
                _fileLog.Error("ShopApiController | MatchShops | Error: Empty paramter.");
                return new Result<List<Shops>>
                {
                    Data = null,
                    Message = "Empty paramter",
                    Status = false
                };
            }

            double dCheckValue;
            if (!double.TryParse(longitude, out dCheckValue) || !double.TryParse(latitude, out dCheckValue))
            {
                _fileLog.Error("ShopApiController | MatchShops | Error: Invalid paramter.");
                return new Result<List<Shops>>
                {
                    Data = null,
                    Message = "Invalid paramter",
                    Status = false
                };
            }

            try
            {
                var nRadius = 2000;
                var sysConfigBll = new SysConfigBLL();
                var lsSysConfig = sysConfigBll.GetModelList();
                if (lsSysConfig != null && lsSysConfig.Count > 0)
                {
                    nRadius = lsSysConfig[0].SearchShopRadius;
                }

                var lsShop = _shopsBll.GetMatchedShopList(longitude, latitude, nRadius, searchKeyword);
                if (lsShop != null && lsShop.Count > 0)
                {
                    foreach (var s in lsShop)
                    {
                        if (s.ParentId > 0)
                        {
                            var industry = IndustryBLL.Instance.GetModel(s.ParentId);
                            if (industry != null)
                            {
                                s.IndustryName = industry.Name;
                            }
                        }
                        s.ShopSalesQuantity =
                            OrdersBLL.Instance.GetTotalCount("ShopId=" + s.Id + "and OrderStatus=" +
                                                             (int)CommonEnum.OrderStatus.Finished);
                        int cardRuleBaseId = 0;
                        if (s.CanSendCard)
                        {
                            var cardRuleBase = CardRuleBaseBLL.Instance.GetModelByShopId(s.Id);
                            if (cardRuleBase != null)
                            {
                                cardRuleBaseId = cardRuleBase.Id;
                            }
                            var cardRuleDetail = _cloudCardBll.CanCardFilter(cardRuleBaseId, s.Id, 0);
                            string categoryCodeStr = "";
                            if (cardRuleDetail != null)
                            {
                                cardRuleDetail.RemoveAll(c => c.ShowOnHomepage == false);
                                foreach (CardRuleDetail detail in cardRuleDetail)
                                {
                                    bool exists =
                                        categoryCodeStr.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
                                            .Contains(detail.CategoryCode);
                                    if (!exists)
                                    {
                                        categoryCodeStr = categoryCodeStr + detail.CategoryCode + ",";
                                    }
                                }
                            }
                            s.CategoryCodeStr = categoryCodeStr != "" ? categoryCodeStr.TrimEnd(',') : "";
                        }
                    }
                }
                return new Result<List<Shops>>
                {
                    Status = true,
                    Message = "Success",
                    Data = lsShop
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("ShopApiController | MatchShops | Exception: " + ex.Message + ex.StackTrace);
                return new Result<List<Shops>>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = null
                };
            }
        }

        // POST api/ShopApi/GetShopInfo/
        /// <summary>
        /// 根据店铺ID获取店铺信息
        /// </summary>
        /// <param name="shopId">店铺ID</param>
        /// <param name="longitude">longitude</param>
        /// <param name="latitude">latitude</param>
        /// <returns>返回店铺信息</returns>
        [HttpPost]
        public Result<Shops> GetShopInfo(int shopId)
        {
            var checkResult = CheckPermission("ShopApiController | GetShopInfo");
            if (!checkResult.Status)
            {
                return new Result<Shops>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }

            if (shopId == 0)
            {
                _fileLog.Error("ShopApiController | GetShopInfo | Error: Empty paramter.");
                return new Result<Shops>
                {
                    Status = false,
                    Message = "Empty paramter.",
                    Data = null
                };
            }

            try
            {
                var shopInfo = _shopsBll.GetModelByIdWhereIndustryId(shopId);
                if (shopInfo != null)
                {
                    if (shopInfo.ParentId > 0)
                    {
                        var industry = IndustryBLL.Instance.GetModel(shopInfo.ParentId);
                        if (industry != null)
                        {
                            shopInfo.IndustryName = industry.Name;
                        }
                    }
                    shopInfo.ShopSalesQuantity =
                        OrdersBLL.Instance.GetTotalCount("ShopId=" + shopInfo.Id + "and OrderStatus=" +
                                                         (int)CommonEnum.OrderStatus.Finished);
                }
                return new Result<Shops>
                {
                    Status = shopInfo.IsActive,
                    Message = shopInfo.IsActive ? "Success" : "False",
                    Data = shopInfo.IsActive && shopInfo.CanFrontView ? shopInfo : null,
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("ShopApiController | GetShopInfo | Exception: " + ex.Message + ex.StackTrace);
                return new Result<Shops>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = null
                };
            }
        }

        // POST api/ShopApi/GetShopNoticeList/
        /// <summary>
        /// 根据店铺ID获取店铺公告列表
        /// </summary>
        /// <param name="shopId">店铺ID</param>
        /// <returns>返回店铺公告信息列表</returns>
        [HttpPost]
        public Result<List<ShopNotice>> GetShopNoticeList(int shopId)
        {
            var checkResult = CheckPermission("ShopApiController | GetShopNoticeList");
            if (!checkResult.Status)
            {
                return new Result<List<ShopNotice>>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }

            if (shopId == 0)
            {
                _fileLog.Error("ShopApiController | GetShopNoticeList | Error: Empty paramter.");
                return new Result<List<ShopNotice>>
                {
                    Status = false,
                    Message = "Empty paramter.",
                    Data = null
                };
            }

            try
            {
                var lsNotice = _shopNoticeBll.GetModelListByShopId(shopId);
                return new Result<List<ShopNotice>>
                {
                    Status = true,
                    Message = "Success",
                    Data = lsNotice
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("ShopApiController | GetShopNoticeList | Exception: " + ex.Message + ex.StackTrace);
                return new Result<List<ShopNotice>>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = null
                };
            }
        }

        // POST api/ShopApi/GetShopListOfConsumerVisited/
        /// <summary>
        /// 获取用户已进入过（购买过）的店铺
        /// </summary>
        /// <param name="consumerId">消费者ID</param>
        /// <returns>返回用户有过消费行为的店铺列表</returns>
        [HttpPost]
        public Result<List<Shops>> GetShopListOfConsumerVisited(int consumerId)
        {
            var checkResult = CheckPermission("ShopApiController | GetShopListOfCosumerVisited");
            if (!checkResult.Status)
            {
                return new Result<List<Shops>>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }

            if (consumerId <= 0)
            {
                _fileLog.Error("ShopApiController | GetShopListOfCosumerVisited | Error: Empty paramter.");
                return new Result<List<Shops>>
                {
                    Data = null,
                    Message = "Empty paramter",
                    Status = false
                };
            }

            try
            {
                var lsShops = _shopsBll.GetShopListOfConsumerVisited(consumerId);
                return new Result<List<Shops>>
                {
                    Status = true,
                    Message = "Success",
                    Data = lsShops
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("ShopApiController | GetShopListOfCosumerVisited | Exception: " + ex.Message +
                               ex.StackTrace);
                return new Result<List<Shops>>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = null
                };
            }
        }

        // POST api/ShopApi/GetAllShopBriefInfoList/
        /// <summary>
        /// 获取店铺简明信息
        /// </summary>
        /// <param name="isActive">激活状态</param>
        /// <param name="key">验证KEY</param>
        /// <param name="verifyCode">校验码</param>
        /// <returns>返回用户有过消费行为的店铺列表</returns>
        [HttpPost]
        public Result<List<ShopBriefDto>> GetAllShopBriefInfoList(int isActive, string key, string verifyCode)
        {
            var checkResult = CheckPermission("ShopApiController | GetAllShopBriefInfoList");
            if (!checkResult.Status)
            {
                return new Result<List<ShopBriefDto>>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }

            if (isActive < 0 || isActive > 1 || string.IsNullOrWhiteSpace(verifyCode))
            {
                _fileLog.Error("ShopApiController | GetAllShopBriefInfoList | Error: Invalid paramter.");
                return new Result<List<ShopBriefDto>>
                {
                    Status = false,
                    Message = "Invalid parameter",
                    Data = null
                };
            }

            try
            {
                var strLocalEncodeResult = EncryptionLib.Encrypt(isActive + key, Encoding.UTF8);
                if (strLocalEncodeResult != verifyCode)
                {
                    _fileLog.Error("ShopApiController | GetAllShopBriefInfoList | Error: Invalid verify code.");
                    return new Result<List<ShopBriefDto>>
                    {
                        Status = false,
                        Message = "Invalid verify code",
                        Data = null
                    };
                }

                var shopList = _shopsBll.GetShopBriefList(" isActive=" + isActive + " ");
                if (shopList == null || shopList.Count == 0)
                {
                    return new Result<List<ShopBriefDto>>
                    {
                        Status = false,
                        Message = "Cannot get the shop brief info",
                        Data = null
                    };
                }
                return new Result<List<ShopBriefDto>>
                {
                    Status = true,
                    Message = "Success",
                    Data = shopList
                };

            }
            catch (Exception ex)
            {
                _fileLog.Error("ShopApiController | GetAllShopBriefInfoList | Exception: " + ex.Message +
                               ex.StackTrace);
                return new Result<List<ShopBriefDto>>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = null
                };
            }

        }

        /// <summary>
        /// 获取店铺可领取卡卷
        /// </summary>
        /// <param name="shopId">店铺id</param>
        /// <returns></returns>
        [HttpPost]
        public Result<string> GetShopCanCard(int shopId)
        {
            var dt = DateTime.Now.Date;
            int awardLimitMinAmount;
            if (!int.TryParse(ConfigurationManager.AppSettings["AwardLimitMinAmount"], out awardLimitMinAmount))
            {
                awardLimitMinAmount = 20;
            }
            var checkResult = CheckPermission("ShopApiController | GetShopCanCard");
            if (!checkResult.Status)
            {
                return new Result<string>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }
            try
            {
                var shop = ShopsBLL.Instance.GetModel(shopId);
                if (shop == null)
                {
                    return new Result<string>
                    {
                        Status = false,
                        Message = "error:shop is null",
                        Data = null
                    };
                }
                if (!shop.CanSendCard)
                {
                    return new Result<string>
                    {
                        Status = false,
                        Message = "error: shop to open a card",
                        Data = null
                    };
                }
                int cardRuleBaseId = 0;
                var cardRuleBase = CardRuleBaseBLL.Instance.GetModelByShopId(shopId);
                List<CardRuleDetail> timeSpanAwardList = null;
                if (cardRuleBase != null)
                {
                    cardRuleBaseId = cardRuleBase.Id;
                }
                timeSpanAwardList = _cloudCardBll.CanCardFilter(cardRuleBaseId, shopId, awardLimitMinAmount);
                if (timeSpanAwardList == null)
                {
                    return new Result<string>
                    {
                        Status = false,
                        Message = "无可领取卡劵",
                        Data = null
                    };
                }
                timeSpanAwardList.RemoveAll(s => s.ShowOnHomepage == false);
                var strEncodeShopCard = EncryptionLib.Encrypt(JsonLib.ObjectToJsonByJss(timeSpanAwardList), Encoding.UTF8);
                return new Result<string>
                {
                    Status = true,
                    Message = "Success",
                    Data = strEncodeShopCard
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("CloudCardApiController | BatchReceiveCard |Exception:" + ex.Message + ex.StackTrace);
                return new Result<string>
               {
                   Status = false,
                   Message = ex.Message,
                   Data = null
               };
            }
        }

        #region 店铺注册

        /// <summary>
        /// 店铺注册
        /// </summary>
        /// <returns></returns>
        public Result<string> RegisteredShop(string shopInfoJsonEncode, string checkCode)
        {
            var checkResult = CheckPermission("ShopApiController | RegisteredShop");
            if (!checkResult.Status)
            {
                return new Result<string>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null,
                    StatusCode = (int)CommonEnum.ApiStatusCode.接口权限校验失败
                };
            }
            if (string.IsNullOrEmpty(shopInfoJsonEncode))
            {
                _fileLog.Error("ShopApiController | RegisteredShop | Error:shopInfoJsonEncode Empty paramter.");
                return new Result<string>
                {
                    Data = null,
                    Message = "shopInfoJsonEncode:Empty paramter",
                    Status = false,
                    StatusCode = (int)CommonEnum.ApiStatusCode.接口参数错误
                };
            }
       
            //解密订单JSON数据
            var strOrderInfoDecode = EncryptionLib.Decrypt(shopInfoJsonEncode, Encoding.UTF8);
            if (string.IsNullOrWhiteSpace(strOrderInfoDecode))
            {
                _fileLog.Error("ShopApiController | RegisteredShop | Error: Invalid encoded shop info json");
                return new Result<string>
                {
                    Data = null,
                    Message = "Invalid encoded shop info json",
                    Status = false,
                    StatusCode = (int)CommonEnum.ApiStatusCode.参数格式错误
                };
            }
            try
            {
                var shopDtoInfo = JsonTool.JsonToObj<ShopsDto>(strOrderInfoDecode);
                if (shopDtoInfo == null || string.IsNullOrWhiteSpace(shopDtoInfo.UserName) ||
                    string.IsNullOrEmpty(shopDtoInfo.PasswordHash) ||
                    string.IsNullOrEmpty(shopDtoInfo.Name) || string.IsNullOrEmpty(shopDtoInfo.Address) ||
                    string.IsNullOrEmpty(shopDtoInfo.LegalPersonMobile) ||
                    string.IsNullOrEmpty(shopDtoInfo.LegalPerson) || shopDtoInfo.IndustryId < 1 ||
                    shopDtoInfo.SeparatedIndustryId < 1 ||
                    string.IsNullOrWhiteSpace(shopDtoInfo.Longitude) || string.IsNullOrWhiteSpace(shopDtoInfo.Latitude))
                {
                    _fileLog.Error("ShopApiController | RegisteredShop | Error: Empty paramter.");
                    return new Result<string>
                    {
                        Data = null,
                        Message = "Empty paramter",
                        Status = false,
                        StatusCode = (int)CommonEnum.ApiStatusCode.参数不全
                    };
                }
                var message = SmsRecordBLL.Instance.CheckCode(shopDtoInfo.LegalPersonMobile, checkCode, (int)CloudCardEnum.SmsRecordUserActionSource.商家账户注册);
                if (message == null || checkCode != message.SendCode)
                {
                    _fileLog.Error("ShopApiController | RegisteredShop | 效验码错误");
                    return new Result<string>
                    {
                        Data = null,
                        Message = "效验码错误",
                        Status = false,
                        StatusCode = (int)CommonEnum.ApiStatusCode.效验码错误
                    };
                }
                var mkysProjectInfo = GetCurrentMatrixCloudProjectInfo(MkysMcId);
                if (mkysProjectInfo == null || mkysProjectInfo.Id == 0)
                {
                    _fileLog.Error("ShopApiController | RegisteredShop | Error: 项目验证失败");
                    return new Result<string>
                    {
                        Data = null,
                        Message = "项目验证失败",
                        Status = false,
                        StatusCode = (int)CommonEnum.ApiStatusCode.项目验证失败
                    };
                }
                var isShop = ShopsBLL.Instance.GetModelByName(shopDtoInfo.Name);
                if (isShop != null && isShop.Id > 0)
                {
                    _fileLog.Error("ShopApiController | RegisteredShop | Error: 店铺名称已经注册");
                    return new Result<string>
                    {
                        Data = null,
                        Message = "店铺名称已经注册",
                        Status = false,
                        StatusCode = (int)CommonEnum.ApiStatusCode.店铺名称已经注册
                    };
                }
                var isMcAccounts = McAccountsBLL.Instance.GetModelList(string.Format("UserName='{0}'", shopDtoInfo.UserName)).FirstOrDefault();
                if (isMcAccounts != null && isMcAccounts.Id > 0)
                {
                    _fileLog.Error("ShopApiController | RegisteredShop | Error: 用户名已经注册");
                    return new Result<string>
                    {
                        Data = null,
                        Message = "用户名已经注册",
                        Status = false,
                        StatusCode = (int)CommonEnum.ApiStatusCode.用户名已经注册
                    };
                }
                var now = DateTime.Now;
                var coordinateStr = CoordinateTransform.BD_WG84(Convert.ToDouble(shopDtoInfo.Longitude), Convert.ToDouble(shopDtoInfo.Latitude));
                var newId = ShopsBLL.Instance.Add(new Shops
                   {
                       Address = shopDtoInfo.Address,
                       AreaId = 0,
                       BusinessStatus = 1,
                       CanFrontView = true,
                       CanSendCard = true,
                       Created = now,
                       Enabled = true,
                       IndustryId = shopDtoInfo.IndustryId,
                       IsActive = true,
                       IsDelete = false,
                       IsHeadquarters = false,
                       IsOpenOrderGrab = false,
                       Latitude = coordinateStr[1].ToString(),
                       LegalPerson = shopDtoInfo.LegalPerson,
                       LegalPersonMobile = shopDtoInfo.LegalPersonMobile,
                       Longitude = coordinateStr[0].ToString(),
                       Name = shopDtoInfo.Name,
                       ParentShopId = 0,
                       SeparatedIndustryId = shopDtoInfo.SeparatedIndustryId,
                       WechatParamQrCodeId = 0, IsCoordinateTransform=true
                   });
                if (newId > 0)
                {
                    ShopSubsidiaryInfoBLL.Instance.Add(new ShopSubsidiaryInfo()
                    {
                        ShopId = newId,
                        AddTime = now,
                        AccountMoney = 8,//赠送8元余额
                        TotaChargeMoney = 8,//赠送8元余额
                        TotalCanSendCard = 200//赠送200次发卡次数
                    });
                    //添加赠送充值记录
                    ShopMoneyChangeRecordBLL.Instance.Add(new ShopMoneyChangeRecord
                    {
                        MxProjectInfoId = 1,
                        AfterMoney = 8,
                        ChangeSource = (int)CloudCardEnum.MerchantMoneyChangeSource.注册店铺系统赠送,
                        ChangeMoney = 8,
                        OperaSource = (int)CloudCardEnum.MerchantMoneyOperaSource.平台,
                        OperaResult = (int)CloudCardEnum.MerchantMoneyOperaResult.操作成功,
                        AddTime = now,
                        ShopId = newId
                    });

                    var model = new McAccounts
                    {
                        PasswordHash = EncryptionLib.Encrypt(shopDtoInfo.PasswordHash),
                        AccountType = 1,
                        LockoutEnabled = false,
                        LockoutUntil = now,
                        AccessFailedCount = 0,
                        CreatedBy = 0,
                        UpdatedBy = 0,
                        Created = now,
                        Updated = now,
                        UserName = shopDtoInfo.UserName,
                        ShopId = newId,
                        Mobile = shopDtoInfo.LegalPersonMobile,
                        DisplayName = shopDtoInfo.LegalPerson,
                    };
                    int result = McAccountsBLL.Instance.AddWithQrParam(model, mkysProjectInfo);
                    if (result <= 0)
                        return new Result<string>
                        {
                            Status = false,
                            Message = "店铺注册失败",
                            Data = null,
                            StatusCode = (int)CommonEnum.ApiStatusCode.店铺注册失败
                        };
                    if (!string.IsNullOrEmpty(model.Mobile))
                    {
                        var sendContent = string.Format(ConfigurationManager.AppSettings["SendContent"], model.UserName, EncryptionLib.Decrypt(model.PasswordHash));
                        SmsRecordBLL.Instance.SendSms(model.Mobile, sendContent, CommonEnum.SmsRecordSendFrom.Api, CommonEnum.SmsRecordUserActionSource.AddBoss);
                    }
                    var arModel = new McAccountRole { AccountId = result, RoleId = 1, IsDelete = false };
                    McAccountRoleBLL.Instance.Add(arModel);
                    SmsRecordBLL.Instance.Delete(message.Id);
                    return new Result<string>
                    {
                        Status = true,
                        Message = "Success",
                        Data = null,
                        StatusCode = (int)CommonEnum.ApiStatusCode.成功
                    };
                }
                return new Result<string>
                {
                    Status = false,
                    Message = "店铺注册失败",
                    Data = null,
                    StatusCode = (int)CommonEnum.ApiStatusCode.店铺注册失败
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("ShopApiController | RegisteredShop | Exception:" + ex.Message + ex.StackTrace);
                return new Result<string>
                  {
                      Status = false,
                      Message = "Exception:" + ex.Message,
                      Data = null,
                      StatusCode = (int)CommonEnum.ApiStatusCode.系统错误
                  };
            }
        }
        #endregion

    }
}
